import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

import * as SockJS from 'sockjs-client';
import * as Stomp from 'stompjs';

@Component({
  selector: 'app-socket',
  templateUrl: './socket.component.html',
  styleUrls: ['./socket.component.css']
})
export class SocketComponent implements OnInit {

  host = 'http://192.168.0.9:8084';

  url1 = `${this.host}/web-socket`;

  sendUrl = `/app/test`;

  stompClient: any;

  message: string;

  @ViewChild('input') input: ElementRef;

  constructor() { }

  ngOnInit() {
  }


  connect() {
    const socket = new SockJS(this.url1);
    this.stompClient = Stomp.over(socket);
    console.log(this.stompClient);
    const headers = {
      // Authorization: `Bearer cde2489d-8b8c-43fd-b3f5-43b8eb922d00`
      Authorization: `Bearer a154dd0d-2814-4cb9-83bd-c521ca5d1651`
    };
    this.stompClient.connect(headers, (frame) => {
      console.log('Connected: ' + frame);

      this.stompClient.subscribe('/user/queue/notify', (greeting) => {
        this.showGreeting(JSON.parse(greeting.body).content);
      });

    });
  }

  connect2() {
    /* const url = 'ws://192.168.0.19:8080/gs-guide-websocket';
    const socket = new SockJS(url);
    console.log(socket)

    this.stompClient = Stomp.overWS(url);
    this.stompClient.connect({}, (frame) => {

      console.log('Connected: ' + frame);
      this.stompClient.subscribe(this.host + '/topic/greetings', (greeting) => {
        this.showGreeting(JSON.parse(greeting.body).content);
      });
    }); */
  }

  disconnect() {
    if (this.stompClient !== null) {
      this.stompClient.disconnect();
      this.stompClient = undefined;
    }
  }

  sendMsg() {
    const name = this.input.nativeElement.value;
    console.log(name);
    this.stompClient.send(this.sendUrl, {}, JSON.stringify({ 'token': name }));
  }

  showGreeting(msg) {
    console.log(msg);
    this.message = msg;
  }

}
